package com.dahua.messagesyncsh.rabbitmq.messageListener;

import com.alibaba.fastjson2.JSON;
import com.dahua.messagesyncsh.pojo.T485;
import com.dahua.messagesyncsh.rabbitmq.pojo.H485;
import com.dahua.messagesyncsh.service.ProcessorService;
import com.dahua.messagesyncsh.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.BatchMessageListener;
import org.springframework.amqp.core.Message;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class HitachiMessageListener implements BatchMessageListener {

    @Resource
    private ProcessorService processorService;

    @Override
    public void onMessage(Message message) {
        BatchMessageListener.super.onMessage(message);
    }

    @Override
    public void onMessageBatch(List<Message> messages) {
        List<T485> t485s = new ArrayList<>();
        for (Message message : messages) {
            try {
                H485 h485 = JSON.parseObject(message.getBody(), H485.class);
                if (h485 == null || h485.getEquipmentId() == null || h485.getDataTime() == null || h485.getManufacturer() == null || h485.getData() == null) {
                    log.error("【Hitachi】: H485数据格式错误{}", h485);
                }
                T485 t485 = T485.build(h485);
                if (t485 == null) {
                    continue;
                }

                if (ObjectUtil.checkNullField(t485)){
                    log.error("【Hitachi】: 数据不完整{}", t485);
                }

                /*  日立扶梯状态切换的时候，寄存器全0*/
                boolean allZero = true;
                for (Integer[] data : t485.getData()){
                    if (data[1] != 0) {
                        allZero = false;
                        break;
                    }
                }
                if (allZero) {
                    log.error("【Hitachi】: 数据全为0{}", t485);
                    continue;
                }

                t485s.add(t485);

            } catch (Exception e) {
                log.error("【Hitachi】: 数据转换错误{} \n {}", message.getBody(), e.toString());
            }
        }
        processorService.handleT485(t485s);
    }
}
